from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.shortcuts import render

# Create your views here.
from django.views import View
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from xj_users.models import Channel, Article, Label, Comment
from cwd_articles.serializers import ChannelSerializer, ArticleCreateSerializer, ArticleRetrieveSerializer, \
    ArticleListSerializer, \
    ArticleCommentSerializer, ArticleIndexSerializer, ArticleSerializerForList
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.pagination import PageNumberPagination
from drf_haystack.viewsets import HaystackViewSet


class PageNum(PageNumberPagination):
    page_size = 5  # 后端指定每页显示数量
    page_size_query_param = 'pagesize'
    max_page_size = 10

    # 重写分页返回方法，按照指定的字段进行分页数据返回
    def get_paginated_response(self, data):
        return Response({
            'count': self.page.paginator.count,  # 总数量
            'next': self.get_next_link(),  # 下页地址
            'previous': self.get_previous_link(),  # 当上页地址
            'results': data
        })

# 文章频道列表
class ChannelView(ListAPIView):
    serializer_class = ChannelSerializer
    queryset = Channel.objects.all()
    pagination_class = PageNum

# 文章相关操作
class ArticleViewSet(ModelViewSet):
    pagination_class = PageNum
    lookup_value_regex = '[\\+\\-]?[\\d]+(\\.[\\d]+)?'

    def get_serializer_class(self):
        if self.action == 'create':
            return ArticleCreateSerializer
        if self.action == 'retrieve':
            return ArticleRetrieveSerializer
        if self.action == 'channel_articles':
            return ArticleListSerializer
        if self.action == 'publish_comment':
            return ArticleCommentSerializer

    # 浏览量 + 1
    def get_object(self):
        obj = super(ArticleViewSet, self).get_object()
        if self.action == 'retrieve':
            # 当请求方法是查询文章时对浏览量+1
            obj.visits += 1
            obj.save()
        return obj

    # 获取文章列表
    def get_queryset(self):
        if self.action == 'channel_articles':
            pk = int(self.kwargs.get(self.lookup_field))
            # 指定文章详情
            if pk != -1:
                return Article.objects.filter(channel_id=pk)
        return Article.objects.all()

    # POST /article/ 创建文章
    def create(self, request, *args, **kwargs):
        '''
        # 创建序列化器
        # 反序列化参数校验
        # 响应数据
        '''


        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        article = serializer.save()
        return Response({'articleid': article.id,
                         'message': '创建成功', 'success': True})

    # GET 获取某个频道之下的文章列表
    @action(detail=True, url_path='channel')
    def channel_articles(self, request, *args, **kwargs):
        return self.list(self, request, *args, **kwargs)

    # PUT /article/{id}/collect/
    @action(detail=True, url_path='collect', methods=['PUT'], permission_classes=[IsAuthenticated])
    def collect_article(self, request, *args, **kwargs):
        '''
        :param kwargs:
        :return:
        '''
        # 获取当前操作的文章
        article = self.get_object()
        # 收藏当前文章的用户列表
        # 当前登录的用户
        user = request.user
        if article.collected_users.filter(id=user.id):
            article.collected_users.remove(request.user)
            return Response({"message": "取消收藏成功", "success": True})
        else:
            article.collected_users.add(request.user)
            return Response({"message": "收藏成功", "success": True})

    # POST /article/{id}/publish_comment/
    @action(detail=True, methods=['POST'], permission_classes=[IsAuthenticated])
    def publish_comment(self, request, *args, **kwargs):

        return self.create(request, *args, **kwargs)


# 图片搜索
class ArticleSearchViewSet(HaystackViewSet):
    index_models = [Article]
    serializer_class = ArticleIndexSerializer

